//
//  NewestViewController.m
//  livingDesign
//
//  Created by dlios on 15-1-28.
//  Copyright (c) 2015年 怡居. All rights reserved.
//
// NSString *const MJCollectionViewCellIdentifier = @"Cell";
#import "NewestViewController.h"
#import "ASIHTTPRequest.h"
#import "Newest.h"
#import "NewestDetailViewController.h"
#import "NewestTopView.h"
#import "NewestMiddleView.h"
#import "NewestMiddleCollectionViewCell.h"
#import "SouSuoViewController.h"
#import "MJRefresh.h"

@interface NewestViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) NSMutableArray *newestArr;  // 保存数据数组
@property (nonatomic, retain) Newest *newest;   // Model对象
@property (nonatomic, retain) NewestTopView *newestTop; // 顶部铺设
@property (nonatomic, retain) NewestMiddleView *newestMiddle;
@property (nonatomic, retain) UIScrollView *scrollerView;
@property (nonatomic, strong) NSMutableArray *refreshArr;  // 刷新数组
@property (nonatomic, assign) NSInteger newestArrNum;
@property (nonatomic, assign) NSInteger tag;
@end

@implementation NewestViewController
- (void)dealloc
{
    [_newest release];
    [_newestArr release];
    [_newestTop release];
    [_newestMiddle release];
    [_scrollerView release];
    [_refreshArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.view.backgroundColor = [UIColor whiteColor];
    
    // 初始化数组
    self.newestArr = [NSMutableArray array];
    // 网络请求
    [self requestByASI];

    self.scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, self.view.frame.size.height)];
//    self.scrollerView.contentSize = CGSizeMake(0, self.view.frame.size.height - 64);
    [self.view addSubview:self.scrollerView];
    
    // 界面铺设
    
    self.newestTop = [[NewestTopView alloc] initWithFrame:CGRectMake(5,0, self.view.frame.size.width - 10, self.view.frame.size.height / 4)];
  
    [self.newestTop release];
  
   
    // 内容铺设
    self.newestMiddle = [[NewestMiddleView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 4 + 10, self.view.frame.size.width , self.view.frame.size.height * 2 / 3 )];
    [self.scrollerView addSubview:self.newestMiddle];\
    self.newestMiddle.collectView.delegate = self;
    self.newestMiddle.collectView.dataSource = self;
     self.newestMiddle.collectView.alwaysBounceVertical = YES;
    // 定义重用池
    [self.newestMiddle.collectView registerClass:[NewestMiddleCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

    
    [self.newestMiddle release];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo.png"] style:UIBarButtonItemStyleDone target:self action:@selector(sousuoAction:)];
    
    // 数组计数赋初值
    self.newestArrNum = 4;
    self.tag = 1;
    
    // 初始化数组
    self.refreshArr = [NSMutableArray array];
    
    
    // 集成新控件
 
   
    
    
}


// 下拉刷新
- (void)addHeader
{
    __unsafe_unretained  typeof(self) vc = self;
//    if (self.newestArr.count != 0) {
    // 添加下拉刷新头部控件
    if (self.newestArrNum != 4) {
    [self.newestMiddle.collectView addHeaderWithCallback:^{
//        if (vc.refreshArr.count == 0) {
//            for (int i = 0; i < 4; i++) {
//                [vc.refreshArr insertObject:[self.newestArr objectAtIndex:i] atIndex:0];
//            }
//        }
       
//        NSLog(@"%@", vc.refreshArr);
        // 模拟延迟加载数据  因此2秒后才调用
        
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,  (int64_t)(1.0 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
                [self.newestMiddle.collectView reloadData];
                NSLog(@"-------------现在总该走刷新了吧");
                [vc.newestMiddle.collectView headerEndRefreshing];
                [self.scrollerView addSubview:self.newestTop];
                
            });

    }];
         }
    [self.newestMiddle.collectView headerBeginRefreshing];
//    }
    
}
// 上拉加载
- (void)addFooter
{
     NSLog(@"*********下拉加载**********");
    __unsafe_unretained  typeof(self) vc = self;
   
       
        // 添加上拉刷新尾部控件
        [self.newestMiddle.collectView addFooterWithCallback:^{
             if (self.tag != 1 && self.newestArrNum <= self.newestArr.count - 1) {
            for (int i = 0; i < 4; i++) {
                if (self.newestArrNum <= self.newestArr.count - 1) {
                    [vc.refreshArr addObject:[self.newestArr objectAtIndex:self.newestArrNum]];
                }
                self.newestArrNum++ ;
                NSLog(@"%ld", self.newestArrNum);
              
                
            }
                   NSLog(@"************刷新数组的数据********%@", vc.refreshArr);
                  }
            // 模拟延迟加载数据  因此2秒后才调用
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,  (int64_t)(1.0 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
                [self.newestMiddle.collectView reloadData];
                [vc.newestMiddle.collectView footerEndRefreshing];
                
            });
        }];
   self.tag = 2;
   
}

//// 刷新数组赋值
- (NSMutableArray *)refreshArr
{
    if (!_refreshArr) {
        self.refreshArr = [NSMutableArray array];
        for (int i = 0; i < 4; i++) {
            [self.refreshArr addObject:[self.newestArr objectAtIndex:self.newestArrNum]];
            self.newestArrNum++;
            NSLog(@"初始化num——————————————%ld", self.newestArrNum);
        }
    }
    return _refreshArr;
}



// 搜索按钮方法
- (void)sousuoAction:(UIBarButtonItem *)barButton
{
    SouSuoViewController *sousuo = [[SouSuoViewController alloc] init];
    [self.navigationController pushViewController:sousuo animated:YES];
    [sousuo release];
}

// 点击到详情页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewestDetailViewController *newest = [[NewestDetailViewController alloc] init];
    newest.newestD = [self.refreshArr objectAtIndex:indexPath.item];
    [self.navigationController pushViewController:newest animated:YES];
    [newest release];
}

// 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSLog(@"￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥%ld", self.refreshArr.count);
    return self.refreshArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
    NewestMiddleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
//
    
    Newest *newest = [self.refreshArr objectAtIndex:indexPath.item];
    NSLog(@">>>>>>>>>>>>>>>>>%@", newest);
    cell.newest = newest;
    //    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}


// 网络请求
- (void)requestByASI
{
    // 使用ASI网络请求
    NSString *pathStr = @"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=0&category=jiaju&category2=&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0";
    NSURL *url = [NSURL URLWithString:pathStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
 
}


//ASI的协议方法

- (void)requestFinished:(ASIHTTPRequest *)request
{
    // 解析数据
    NSData *data = [request responseData];
    NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *tempArr = [tempDic objectForKey:@"data"];
    for (NSDictionary *dataDic in tempArr) {
        self.newest = [[Newest alloc] init];
        [self.newest setValuesForKeysWithDictionary:dataDic];
        [self.newestArr addObject:self.newest];
        [self.newest release];
    }
    self.newestMiddle.arr = self.newestArr;
    NSLog(@"2222222222222222222222222222222222%ld", self.newestArr.count);
    for (int i = 0; i < 4; i++) {
        [self.refreshArr insertObject:[self.newestArr objectAtIndex:i] atIndex:0];
    }
    [self.newestMiddle.collectView reloadData];
     [self addHeader];
     [self addFooter];
   
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"请求失败");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
